package com.web.handler.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.web.common.ReturnCode;
import com.web.handler.entity.QuotePrice;
import com.web.handler.mapper.QuotePriceMapper;
import com.web.rate.service.RateService;

@Service
public class QuotePriceService {

	@Autowired
    private QuotePriceMapper mapper;

	@Autowired
    private RateService rateService;

	public void addQuotePrice(QuotePrice qp) {
		mapper.addQuotePrice(qp);
	}

	public void amendQuotePrice(QuotePrice qp) {
		mapper.amendQuotePrice(qp);
	}

	public void checkInput(QuotePrice qp) {
		//TODO 配置币种表后校验币种是否存在

		if(qp.getAmount1() == null && qp.getAmount2() == null) {
			qp.setReturnCode(ReturnCode.BOTH_SIDE_AMT_NOT_INPUT);
		}
		if(qp.getAmount1() != null && qp.getAmount2() != null) {
			qp.setReturnCode(ReturnCode.BOTH_SIDE_AMT_INPUT);
		}
	}

	public void calculateAmt(QuotePrice qp) {
		if(qp.isContainUSD()) {
			if(qp.isCurrency1USD()) {
				BigDecimal rate = rateService.getRate(qp.getCurrency2(), qp.getBuySellOption()).getRate();
				if(qp.getAmount1() == null) {
					qp.setAmount1(qp.getAmount2().divide(rate, 2, RoundingMode.HALF_DOWN));
				}else {
					qp.setAmount2(qp.getAmount1().multiply(rate).setScale(2, RoundingMode.HALF_DOWN));
				}
				qp.setBankCostRate(rate);
			}else {
				BigDecimal rate = rateService.getRate(qp.getCurrency1(), qp.getBuySellOption()).getRate();
				if(qp.getAmount1() == null) {
					qp.setAmount1(qp.getAmount2().multiply(rate).setScale(2, RoundingMode.HALF_DOWN));
				}else {
					qp.setAmount2(qp.getAmount1().divide(rate, 2, RoundingMode.HALF_DOWN));
				}
				qp.setBankCostRate(rate);
			}
		}else {
			BigDecimal currency1Rate = rateService.getRate(qp.getCurrency1(), qp.getBuySellOption()).getRate();
			BigDecimal currency2Rate = rateService.getRate(qp.getCurrency2(), qp.getBuySellOption()).getRate();
			if(qp.getAmount1() == null) {
				qp.setAmount1(qp.getAmount2().divide(currency2Rate, 2, RoundingMode.HALF_DOWN).multiply(currency1Rate).setScale(2, RoundingMode.HALF_DOWN));
			}else {
				qp.setAmount2(qp.getAmount1().divide(currency1Rate, 2, RoundingMode.HALF_DOWN).multiply(currency2Rate).setScale(2, RoundingMode.HALF_DOWN));
			}
			qp.setBankCostRate(currency2Rate.divide(currency1Rate,7, RoundingMode.HALF_DOWN).setScale(7, RoundingMode.HALF_DOWN));
		}
	}

	public List<Map<String,String>> getEcharts(){
		return mapper.getEchartsData();
	}
}
